<?php
	session_start();
    if(!isset($_SESSION["userName"]) or $_SESSION["userType"] !== "qc") {
    	header("location: accesserror.php");
    }
    header("text/html;charset=utf8");
	$result = "?result=";
	$project = trim($_POST['project']);
	$startTime = trim($_POST['startTime']);
	$city = trim($_POST['city']);
	$storeNum = trim($_POST['storeNum']);
	$storeName = trim($_POST['storeName']);
	$storeAddress = trim($_POST['storeAddress']);
	$questionNum = trim($_POST['questionNum']);
	if ($project === "" or $startTime === "" or $city === "" or $storeNum === "" or $storeName === "" or $storeAddress === ""
		or !isset($_POST['supervisors']) or !isset($_POST["inspecters"]) or $questionNum === "") { 
	  		$result .= "必填项不能为空";
	} 
	else {
  		$connect = mysql_connect("localhost","root","yxs147789");
		if ($connect) {
			$success = true;
		  	mysql_select_db("inspectdb", $connect);
		  	mysql_query("set names 'utf8'");
		  	$problemsSql = sprintf("INSERT INTO problems (project, start_time, city, store_num, store_name, store_address, question_num)" .
		  		"VALUES ('%s', '%s','%s', '%s', '%s', '%s', '%s')", $project, $startTime, $city, $storeNum, $storeName, $storeAddress, $questionNum);
		  	if(!mysql_query($problemsSql)) {
		  		$result .= "创建失败";
		  	} else { 
		  		$id = mysql_insert_id();
		  		mysql_query("BEGIN");
		  		$supervisors = $_POST["supervisors"];
		  		$inspecters = $_POST["inspecters"];
		  		$problemInfoStr = "INSERT INTO problem_info (problem_id, user_name, user_type) VALUES ('%s', '%s', '%s')";
		  		//创建督导表
		  		$success = mysql_query(sprintf($problemInfoStr, $id, $_SESSION["userName"], "qc"));
		  		foreach($supervisors as $index_s=> $supervisor) { 
		  			$success = mysql_query(sprintf($problemInfoStr, $id, $supervisor, "supervisor"));
		  		}
		  		//创建调查员表
		  		foreach($inspecters as $index_i=> $inspecter) { 
		  			$success = mysql_query(sprintf($problemInfoStr, $id, $inspecter, "inspecter"));
		  		}
		  		if($success) { 
		  			mysql_query("COMMIT");
		  			$result .= "success&id=".$id;
		  		} else { 
		  			mysql_query("ROLLBACK");
		  			$result .= "创建失败";
		  		}
		  		mysql_query("END");
		  	}
		} else {
			$result .= "连接失败";
		}
		mysql_close($connect);
	}
	header("location: createproblem.php" . $result);
?>